//
//  CreateStoreVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/3.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import Eureka
import SVProgressHUD
protocol createStoreDelegate: class {
    func didCreateStore(bool: Bool)
}

class CreateStoreVC: FormViewController {
    
    
    let lists = ["商号简称", "商号全称", "手机", "成立时间", "主营", "地址", "资料证明"]
    let storeVCHelper = StoreVCHelper()
    
    weak var delegate: createStoreDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        DateRow.defaultRowInitializer = { row in row.minimumDate = Date() }
        
        ImageRow.defaultCellUpdate = { cell, row in
            cell.height = { 65 }
            cell.accessoryView?.layer.cornerRadius = 30
            cell.accessoryView?.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
        }
        LabelRow.defaultCellUpdate = { cell, row in
            cell.contentView.backgroundColor = .red
            cell.textLabel?.textColor = .white
            cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13)
            cell.textLabel?.textAlignment = .right
            
        }
        
        
        form +++
            Section("为您的商店添加图标")
            
            <<< ImageRow() {
                $0.title = "Logo"
                $0.add(rule: RuleRequired())
                $0.validationOptions = .validatesOnChange
                }
                .cellUpdate { cell, row in
                    if !row.isValid {
                        cell.textLabel?.textColor = .red
                    }
                }
                .onRowValidationChanged { cell, row in
                    let rowIndex = row.indexPath!.row
                    while row.section!.count > rowIndex + 1 && row.section?[rowIndex  + 1] is LabelRow {
                        row.section?.remove(at: rowIndex + 1)
                    }
                    if !row.isValid {
                        for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
                            let labelRow = LabelRow() {
                                $0.title = validationMsg
                                $0.cell.height = { 30 }
                            }
                            row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
                        }
                    }
            }
            +++ Section()
            
            <<< TextRow() {
                $0.title = lists[0]
                $0.placeholder = lists[0]
                $0.add(rule: RuleRequired())
                $0.validationOptions = .validatesOnChange
                }
                .cellUpdate { cell, row in
                    if !row.isValid {
                        cell.titleLabel?.textColor = .red
                    }
                }
                .onRowValidationChanged { cell, row in
                    let rowIndex = row.indexPath!.row
                    while row.section!.count > rowIndex + 1 && row.section?[rowIndex  + 1] is LabelRow {
                        row.section?.remove(at: rowIndex + 1)
                    }
                    if !row.isValid {
                        for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
                            let labelRow = LabelRow() {
                                $0.title = validationMsg
                                $0.cell.height = { 30 }
                            }
                            row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
                        }
                    }
            }
            <<< TextRow() {
                $0.title = lists[1]
                $0.placeholder = lists[1]
                $0.add(rule: RuleRequired())
                $0.validationOptions = .validatesOnChange
                }
                .cellUpdate { cell, row in
                    if !row.isValid {
                        cell.titleLabel?.textColor = .red
                    }
                }
                .onRowValidationChanged { cell, row in
                    let rowIndex = row.indexPath!.row
                    while row.section!.count > rowIndex + 1 && row.section?[rowIndex  + 1] is LabelRow {
                        row.section?.remove(at: rowIndex + 1)
                    }
                    if !row.isValid {
                        for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
                            let labelRow = LabelRow() {
                                $0.title = validationMsg
                                $0.cell.height = { 30 }
                            }
                            row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
                        }
                    }
                    
            }
            <<< PhoneRow() {
                $0.title = lists[2]
                $0.value = "+86 \(User.phoneNumber!)"
                $0.disabled = true
            }
            
            <<< DateRow() {
                $0.minimumDate = Date(timeIntervalSince1970: 0)
                $0.maximumDate = Date(timeIntervalSinceNow: 0)
                $0.value = Date()
                $0.title = lists[3]
                $0.add(rule: RuleRequired())
                $0.validationOptions = .validatesOnChange
                }
                .cellUpdate { cell, row in
                    if !row.isValid {
                        cell.textLabel?.textColor = .red
                    }
                }
                .onRowValidationChanged { cell, row in
                    let rowIndex = row.indexPath!.row
                    while row.section!.count > rowIndex + 1 && row.section?[rowIndex  + 1] is LabelRow {
                        row.section?.remove(at: rowIndex + 1)
                    }
                    if !row.isValid {
                        for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
                            let labelRow = LabelRow() {
                                $0.title = validationMsg
                                $0.cell.height = { 30 }
                            }
                            row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
                        }
                    }
                    
            }
            <<< TextRow() {
                $0.title = lists[4]
                $0.placeholder = lists[4]
                $0.add(rule: RuleRequired())
                $0.validationOptions = .validatesOnChange
                }
                .cellUpdate { cell, row in
                    if !row.isValid {
                        cell.titleLabel?.textColor = .red
                    }
                }
                .onRowValidationChanged { cell, row in
                    let rowIndex = row.indexPath!.row
                    while row.section!.count > rowIndex + 1 && row.section?[rowIndex  + 1] is LabelRow {
                        row.section?.remove(at: rowIndex + 1)
                    }
                    if !row.isValid {
                        for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
                            let labelRow = LabelRow() {
                                $0.title = validationMsg
                                $0.cell.height = { 30 }
                            }
                            row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
                        }
                    }
                    
                }
            
            <<< TextRow() {
                $0.title = lists[5]
                $0.placeholder = lists[5]
                $0.add(rule: RuleRequired())
                $0.validationOptions = .validatesOnChange
                }
                .cellUpdate { cell, row in
                    if !row.isValid {
                        cell.titleLabel?.textColor = .red
                    }
                }
                .onRowValidationChanged { cell, row in
                    let rowIndex = row.indexPath!.row
                    while row.section!.count > rowIndex + 1 && row.section?[rowIndex  + 1] is LabelRow {
                        row.section?.remove(at: rowIndex + 1)
                    }
                    if !row.isValid {
                        for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
                            let labelRow = LabelRow() {
                                $0.title = validationMsg
                                $0.cell.height = { 30 }
                            }
                            row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
                        }
                    }
                    
            }
            
        
        +++ Section("提交商店认证资料")
            <<< ImageRow() {
                $0.title = lists[6]
                $0.add(rule: RuleRequired())
                $0.validationOptions = .validatesOnChange
                }
                .cellUpdate { cell, row in
                    if !row.isValid {
                        cell.textLabel?.textColor = .red
                    }
                }
                .onRowValidationChanged { cell, row in
                    let rowIndex = row.indexPath!.row
                    while row.section!.count > rowIndex + 1 && row.section?[rowIndex  + 1] is LabelRow {
                        row.section?.remove(at: rowIndex + 1)
                    }
                    if !row.isValid {
                        for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
                            let labelRow = LabelRow() {
                                $0.title = validationMsg
                                $0.cell.height = { 30 }
                            }
                            row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
                        }
                    }
            }
            
        +++ Section()
            <<< ButtonRow() {
                $0.title = "提交认证"
            }
                .onCellSelection { cell, row in
                    let errors = row.section?.form?.validate()
                    guard errors?.count == 0 else {
                        //debugPrint(errors)
                        return
                    }
                    self.view.isUserInteractionEnabled = false
                    SVProgressHUD.show()
                    self.apply()
            }
    }
    
    
    private func apply() {
        guard let logoImage = (form.allRows[0] as! ImageRow).value, let alias = (form.allRows[1] as! TextRow).value, let name = (form.allRows[2] as! TextRow).value, let foundTime = (form.allRows[4] as! DateRow).value, let mainBusiness = (form.allRows[5] as! TextRow).value, let address = (form.allRows[6] as! TextRow).value, let licenseImage = (form.allRows[7] as! ImageRow).value else {
            return
        }
        
        guard let logo = convertToBase64(logoImage), let license = convertToBase64(licenseImage) else {
            return
        }
        storeVCHelper.applyForSeller(with: alias, name: name, address: address, mainBusiness: mainBusiness, foundTime: foundTime.description, license: license, logo: logo) { (success) in
            if success {
                self.delegate?.didCreateStore(bool: true)
                SVProgressHUD.dismiss()
                self.navigationController?.popViewController(animated: true)
                self.view.isUserInteractionEnabled = true
            } else {
                self.showError(message: "提交认证失败，请重试")
                self.delegate?.didCreateStore(bool: false)
                SVProgressHUD.dismiss()
            }
        }
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

//extension CreateStoreVC: UITableViewDelegate, UITableViewDataSource {
//    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        <#code#>
//    }
//}

